package security.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import security.filters.AuthenticationData;

/**
 * 授权工具
 */
public class SecurityAuthUtil {
//
//    /**
//     * 账号ID
//     */
//    private static final String KEY_ACCOUNT_ID = "SECURITY-AUTH-UTIL-ID";
//
//    /**
//     * 账号令牌
//     */
//    private static final String KEY_TOKEN = "SECURITY-AUTH-UTIL-TOKEN";

    /**
     * 数据对象键
     */
    private static final String KEY_DATA = "SECURITY-AUTH-DATA";

    /**
     * 授权完成后的属性写入
     *
     * @param authenticationData
     */
    public static void authorized(AuthenticationData authenticationData) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        requestAttributes.setAttribute(KEY_DATA, authenticationData, RequestAttributes.SCOPE_REQUEST);
    }

    /**
     * 获取当前授权的用户ID
     *
     * @return
     */
    public static long getAccountId() {
        AuthenticationData data = getData();
        if (data != null)
            return data.getId();
        return 0L;
    }

    /**
     * 获取当前授权的TOKEN
     *
     * @return
     */
    public static String getToken() {
        AuthenticationData data = getData();
        if (data != null)
            return data.getToken();
        return null;
    }

    /**
     * 获取当前授权SID
     *
     * @return
     */
    public static long getSid() {
        AuthenticationData data = getData();
        if (data != null)
            return data.getSid();
        return 0L;
    }

    /**
     * 获取当前授权的主体对象
     *
     * @return
     */
    public static AuthenticationData getData() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return (AuthenticationData) requestAttributes.getAttribute(KEY_DATA, RequestAttributes.SCOPE_REQUEST);
    }
}
